package org.gthelper.handler;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import org.gthelper.data.DataGeter;
import org.gthelper.database.UserInfo;
import org.gthelper.error.ErrorCode;
import org.gthelper.order.OrderInfo;
import org.gthelper.security.IchkID;
import org.gthelper.security.ValidationRSA;


/**
 * 预登录
 * @author pig
 */
public class PreLogin extends Handler
{

	@Override
	public int handle(OrderInfo orderinfo) {
		// TODO 自动生成的方法存根
		//get id
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataGeter dg = new DataGeter();
		int errcode=dg.getData(orderinfo.orderStream, baos);
		if(errcode!=ErrorCode.NORMAL)return errcode;
		try {
			String usrid=new String(baos.toByteArray(),"UTF-8");
			
			//get userinfo
			UserInfo userinfo=null;
			try {
				userinfo = UserInfo.getUserInfobyID(usrid);
			} catch (Exception e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
				return ErrorCode.DATABASEERR;
			}
			if(userinfo==null)return ErrorCode.IDNOTEXIST;
			
			//生成密钥
			IchkID chkid = new ValidationRSA();
			Map<String,Object>keyMap = chkid.initKey();
			byte[] pubkey = chkid.getPublicKey(keyMap);
			byte[] prikey = chkid.getPrivateKey(keyMap);
			
			try {
				userinfo.setprivatekey_server(IchkID.encryptBASE64(prikey));
			} catch (Exception e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
				return ErrorCode.DATABASEERR;
			}
			if(!userinfo.UpdateUserInfo())return ErrorCode.DATABASEERR;
			
			//返回公钥
			DataOutputStream dos = new DataOutputStream(orderinfo.mainOutput);
			try {
				dos.writeLong((long)(pubkey.length));
				dos.write(pubkey);
			} catch (IOException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
			
			return ErrorCode.NORMAL;
				
					
		} catch (UnsupportedEncodingException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (Exception e1) {
			// TODO 自动生成的 catch 块
			e1.printStackTrace();
			return ErrorCode.UNKNOWN;
		}
		return ErrorCode.NORMAL;
	}
	
	
	
	
}